﻿using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Infrastructure
{
    /// <summary>
    /// 应用程序全局访问器（静态服务定位器模式）
    /// 提供对当前HTTP上下文、依赖注入服务和用户信息的全局访问入口
    /// </summary>
    /// <remarks>
    /// 典型使用场景：
    /// 1. 在无法使用依赖注入的静态方法中获取服务
    /// 2. 在中间件或过滤器等位置快速访问当前上下文
    /// 3. 需要全局访问应用程序服务的特殊场景
    ///
    /// 警告：优先使用构造函数注入，此模式应作为最后手段
    /// </remarks>
    public static class App
    {
        private static IHttpContextAccessor _httpContextAccessor;

        public static void Initialize(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
        }

        public static IServiceProvider ServiceProvider =>
            HttpContext?.RequestServices ?? IApp.ServiceProvider;

        public static HttpContext HttpContext => _httpContextAccessor?.HttpContext;

        public static ClaimsPrincipal User => HttpContext?.User;

        public static T GetService<T>() where T : class =>
            ServiceProvider.GetService<T>();

        public static object GetService(Type type) =>
            ServiceProvider.GetService(type);

        public static T GetRequiredService<T>() where T : class =>
            ServiceProvider.GetRequiredService<T>();

        public static object GetRequiredService(Type type) =>
            ServiceProvider.GetRequiredService(type);
    }

   
}